
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
var wxFailAuth = true;
var inviteuid = '';
Page({

  /**
     * 页面的初始数据
     */
  data: {
    tc: 0,
    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    uid: '',
    token: '',
    openid: 0,
    userinfo: {},
    article: '',
    peopleAvatar:[],

    hongbaoData: {}, //红包数据
    hongbaoId: '',//红包id
    shareuid: '', //分享者id
    huaCount: 0, //花的数量
    getHongBaoCount: 0,//当前这个分享者领取红包个数
    getTotalMoney: 0, //当前这个分享者领取的红包总额
    hongbaoJin_e: 0, //当次开红包所得金额
    hoongbao_getover: '',//红包是否领完了

    hasMingPian: false,

    hasShare: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })

    inviteuid = '';
    
    var tc = app.get_tc();
    var that = this;
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('hongbao', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
        tc: tc
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x
        })
      }
    })

    inviteuid = options.inviteuid ? options.inviteuid : '';
    
    var share = false;
    if(inviteuid){
        share = true;
    }
    this.setData({
      //红包id
      hongbaoId: options.hongbaoid,
      //分享者id
      shareuid: options.shareuid,
      //是否是分享进来的
      hasShare: share
    });
    
    app.LoginUserInfo(function (res) {
      wxFailAuth = res == -1;
      if(!wxFailAuth){
        var cata = (parseInt(res.usercata) > 0) ? true : false;
        that.setData({
          userinfo: res,
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid,
          hasMingPian: cata
        });
      }
      that.getHongbaoInfo();
    }, inviteuid);
  },

  onShow:function(){
    var that = this;
    // app.LoginUserInfo(function (res) {
    //   wxFailAuth = res == -1;
    //   if (!wxFailAuth) {
    //     var cata = (parseInt(res.usercata) > 0) ? true : false;
    //     that.setData({
    //       userinfo: res,
    //       uid: res.uid,
    //       token: res.token,
    //       openid: res.wxsmall_openid,
    //       hasMingPian: cata
    //     });
    //   }
    //   that.getHongbaoInfo();
    // }, inviteuid);
  },

  goTixianPage: function(e) {
    // {{uid }}
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
    } else {
      wx.navigateTo({ url: "/pages/tixian/tixian?uid=" + this.data.uid });
      app.saveFormId(e.detail.formId);
    }
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    if (url) {
      wx.navigateTo({ url: url })
    }
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //获取红包信息
  getHongbaoInfo: function () {
    var that = this;
    var params = {
      ac: "hongbaocontent",
      publickey: util.publiccode,
      shareuid: that.data.shareuid,
      hongbaoid: that.data.hongbaoId,
      uid: that.data.uid
    };
    console.log('获取红包信息: ', params);

    util.api({
      data: params,
      success: function (responseData) {
        //更新数据
        console.log('hongbao: ', responseData);

        if (responseData && responseData.statusCode == 200) {
          if (responseData.data.msg) {
            app.dialog(responseData.data.msg, "loading");
          }
          
          var getOver = "";
          var allCount = parseInt(responseData.data.all_count);
          var allGetCount = parseInt(responseData.data.all_getcount);
          var myGetCoin = parseInt(responseData.data.myget_coin);
          if (allGetCount >= allCount) {
            if (myGetCoin > 0) {
              getOver = (myGetCoin / 100.0).toFixed(2);
            }
          } else {
            if (myGetCoin > 0) {
              getOver = (myGetCoin / 100.0).toFixed(2);
            }
          }
          // 转换金额单位
          var shareInfo = responseData.data.shareinfo;
          if(shareInfo) {
            for (var i = 0; i < shareInfo.length; i++) {
              var formatShareNum = (parseInt(shareInfo[i].sharenum) / 100.0).toFixed(2);
              shareInfo[i].sharenum_yuan = formatShareNum;
            }
          }

          var totalMoney = (responseData.data.this_allget_coin / 100.0).toFixed(2);
          that.setData({
            hongbaoData: responseData.data,
            article: responseData.data.html_data,
            huaCount: responseData.data.flower_num,
            getHongBaoCount: responseData.data.this_allget_count,
            getTotalMoney: totalMoney,
            hongbaoJin_e: getOver
          });
          /**
              * WxParse.wxParse(bindName , type, data, target,imagePadding)
              * 1.bindName绑定的数据名(必填)
              * 2.type可以为html或者md(必填)
              * 3.data为传入的具体数据(必填)
              * 4.target为Page对象,一般为this(必填)
              * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
              */
          WxParse.wxParse('article', 'html', that.data.article, that, 10);

          //设置导航标题
          var userName = responseData.data.senduser.username;
          var navtitle = userName + '发福利';
          wx.setNavigationBarTitle({
            title: navtitle
          });
        }
        
        wx.hideLoading();
      }

    });
  },

  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      // wx.reLaunch({ //用这个会报错fail can not invoke relaunch in background
      wx.redirectTo({
        url: '/pages/hongbao/hongbao?hongbaoid=' + that.data.hongbaoId + '&shareuid=' + that.data.shareuid
      })
    }
  },

  //开红包
  kaihongbaoAction: function (e) {
    if(wxFailAuth){
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    wx.showLoading({
      title: '开。。。',
    })
    console.log("formId ", e.detail.formId);
    app.saveFormId(e.detail.formId);//保存fromId

    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'gethongbao' + that.data.token);
    util.api({
      method: "POST",
      data: {
        ac: "gethongbao",
        uid: that.data.uid,
        hongbaoid: that.data.hongbaoId,
        shareuid: that.data.shareuid,
        openid: that.data.openid,
        privatekey: privatekey
      },
      success: function (responseData) {
        console.log("gethongbao ", responseData);
        if (responseData && responseData.statusCode == 200) {
          if (responseData.data.res) {
            var totalMoney = (responseData.data.coin_num / 100.0).toFixed(2);
            wx.showModal({
              title: '赞',
              content: "你开了" + totalMoney + "元",
              showCancel: false
            })
            //刷新数据
            that.getHongbaoInfo(that.data.uid, that.data.token);
          } else {
            if (responseData.data.msg.indexOf("empty") >= 0) {
              var showStr = "领完了";
              that.setData({
                hoongbao_getover: showStr
              });
            }
            app.dialog(responseData.data.msg, " ");
            
          }
        }
        wx.hideLoading();
      }
    });
  },

  shareToPengyouquan: function (e) {
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    app.saveFormId(e.detail.formId);//保存fromId

    var that = this;
    var shareImgUrl = util.api_host + "/wxxcxcode.php?haibao=1&uid=" + that.data.uid +
      "&shareuid=" + that.data.uid + "&hongbaoid=" + that.data.hongbaoId + "&inviteuid=" + that.data.uid;
    
    // this.showEWM(shareImgUrl);
    shareImgUrl = base64.encode(shareImgUrl);
    var url = "/pages/haibao-page/haibao-page?imgUrl=" + shareImgUrl;
    wx.navigateTo({ url: url })
  },

  //页面分享
  onShareAppMessage: function () {
    console.log("onShareAppMessage");
    var that = this;
    var invUid = this.data.uid ? this.data.uid : this.data.shareuid;
    return {
      title: "独乐乐不如众乐乐，有红包抢，必须通知好友",
      path: '/pages/hongbao/hongbao?hongbaoid=' + that.data.hongbaoId + '&shareuid=' + invUid + '&inviteuid=' + invUid
    };
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },

  showEWM: function (url) {
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },


  goAther_miniProgram: function () {
    // wx.showToast({
    //   title: '到通讯录小程序小程序',
    // })
    wx.navigateToMiniProgram({
      appId: 'wx7442ff93f452b7c9',
      path: 'pages/tixian/tixian',
      extarData: {
        open: 'happy'
      },
      envVersion: 'release',
      success(res) {
        wx.clearStorage();
        // wx.showToast({
        //   title: '打开成功',
        // })
      },
      fail(res) {
        wx.showToast({
          title: '打开失败' + JSON.stringify(res),
        })
      }
    })
  }

})